<template>
  <div class='mark_page'>
    <div style="text-align:center;margin-bottom: 20px;">
      选择类型:
      <a-select :default-value="XWatermarkType" style="width: 120px" @change="onTypeChange">
        <a-select-option :value="1"> 主图 </a-select-option>
        <a-select-option :value="2"> 长图 </a-select-option>
        <a-select-option :value="3"> 3:4 </a-select-option>
      </a-select>
    </div>
    <div class="mark_box">
      <div class="mark_canvas" :style="{ width: GCanvasSize.wL + 'px'}">
        <div class="canvas_tools">
          <div class="tools_box" v-if="activeMenu === 2">
            <div class="select">
              <a-input-number style="width: 80px;" :max="500" :min="1" placeholder="字号" v-model="acFontSize" @change="onFontSizeChange" />
              <div class="select_hover">
                <div :class="['select_options', acFontSize === item ? 'active' : '']" v-for="item in fontSizeList" :key="item" :value="item" @click="onSlSize(item)">{{ item }}</div>
              </div>
            </div>
            <!-- <a-select style="width: 80px;margin:0 5px;" show-search v-model="acFontSize" placeholder="请选择字号" @change="onFontSizeChange">
              <a-select-option v-for="item in fontSizeList" :key="item" :value="item"> {{ item }} </a-select-option>
            </a-select> -->
            <input type="color" v-model="fontColor" class="tool_color" @change="onColorChange">
            <a-popover placement="bottom">
              <template slot="content">
                <div class="position_box">
                  <div class="posi_item" v-for="item in 9" :key="item" @click="onPosChange(item)"></div>
                </div>
              </template>
              <i class="iconfont icon-jiugongge" style="fontSize:28px;"></i>
            </a-popover>
          </div>
          <i class="iconfont icon-del tool_del" @click="onDelTarget"></i>
        </div>
        <!-- 大画板 -->
        <div class="canvas_box">
          <img class="canvas_bg" :src="slMainGood.taskPicUrl" alt="">
          <canvas id="canvasId" :width="GCanvasSize.wL" :height="GCanvasSize.hL"></canvas>
        </div>
        <!-- <MarkCom id="canvasId" ref="canvasId"></MarkCom> -->
      </div>
      <div class="mark_menu">
        <a-menu class="edit_menu" mode="inline" theme="light" :selectedKeys="selectedKeys" @click="onSelectMenu">
          <a-menu-item :key="1">模板</a-menu-item>
          <a-menu-item :key="2">文本</a-menu-item>
        </a-menu>
        <div class="edit_box tmp_box" v-if="activeMenu === 1">
          <div class="tmp_list">
            <!-- <div class="list_box scroll_box" @scroll="onScrollTmp"> -->
            <div class="list_box scroll_box">
              <div v-for="item in tmpList" :key="item.templateId">
                <img alt="" :src="item.picUrl" @click="onSlTmp(item, item.templateId)">
                <!-- <div v-for="(jtem, jdx) in item.watermarks" :key="jdx">
                </div> -->
              </div>
            </div>
          </div>

        </div>
        <div class="edit_box text_box" v-if="activeMenu === 2">
          <div class="text_opts">
            <a-button @click="onTextOptChange(1)" style="marginRight: 10px;">添加文字</a-button>
            <a-button @click="onTextOptChange(2)">编辑价格</a-button>
          </div>
          <div class="text_container">
            <!-- 添加文字 -->
            <div v-if="textOpt === 1" class="add_box">
              <div>统一文字描述</div>
              <div class="tips">对于已选择的所有商品,都添加此文字标签</div>
              <a-input v-model="textAreaVal" type="textarea" class="text_area" placeholder="请输入文字" @change="onAddText"></a-input>
            </div>
            <!-- 编辑价格 -->
            <div v-if="textOpt === 2" class="price_box">
              <a-radio-group v-model="priceType" class="price_type" @change="onPriceChange">
                <a-radio :style="radioStyle" :value="1"> 智能价格
                </a-radio>
                <div class="tips" style="marginBottom: 20px;">自动获取聚麦促销设置的最低折扣价（不包含全店折扣、循环打折、定向优惠）</div>
                <a-radio :style="radioStyle" :value="2"> 自定义价格
                </a-radio>
                <div class="tips">手动设置价格</div>
              </a-radio-group>
              <a-button class="btn" type="primary" @click="onPriceEdit">修 改</a-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <a-button @click="onUse" type="primary" style="marginTop:20px;">一键预览</a-button>
    <div class="pic_list">
      <i class="iconfont icon-left icon_left" @click="onScroll(1)"></i>
      <i class="iconfont icon-fanhuizuojiantouxiangzuoshangyibuxianxing icon_right" @click="onScroll(2)"></i>
      <div class="list_box main_goods" ref="mainScroll">
        <div v-for="(item, index) in markGoodsInfo" :key="item.numIid" :class="['img_item', slMainGood.numIid === item.numIid ? 'active' : '']" :style="{ width: GCanvasSize.wS + 'px', height: GCanvasSize.hS + 'px' }" @click="onSlMainGood(item)">
          <MarkCom :id="'main' + item.numIid" :ref="'main' + item.numIid" :srcInfo="item"></MarkCom>
          <div class="mark"></div>
          <div class="del_icon" @click.stop="onDelGoods(item, index)">
            <i class="iconfont icon-left icon-del"></i>
          </div>
        </div>
      </div>
    </div>
    <div>
    </div>
    <!-- 自定义价格设置 -->
    <SetPrice :visible="isSetPrice" @ok="onPriceOk" @close="isSetPrice = false"></SetPrice>
  </div>
</template>

<script>
import { fabric } from 'fabric'
import { mapState, mapMutations } from 'vuex'
import { FabricMixin } from './mixin'
import MarkCom from './MarkCom'
import SetPrice from './SetPrice'
import DataInfo from './data.js'
export default {
  components: { MarkCom, SetPrice },
  computed: {
    ...mapState(['XFabricJson', 'XWatermarkType', 'XShopItems']),
    selectedKeys () {
      return [this.activeMenu]
    }
  },
  mixins: [FabricMixin],
  data () {
    const radioStyle = {
      display: 'block',
      height: '30px',
      lineHeight: '30px'
    }
    return {
      // aLifont,
      radioStyle,
      isTagAll: false,
      fontSizeList: [],
      acFontSize: '',
      fontColor: '#000000',
      activeMenu: 1, // 1模板 2文字
      textOpt: -1, // 1添加文字 2编辑价格
      priceType: 1, // 1智能 2自定义
      XProductIds: [1],
      tmpList: [],
      slMainGood: {
        taskPicUrl: ''
      },
      slTmp: {}, // 已选模板
      tmpId: '', // templateId
      acTarget: null,
      textAreaVal: '',
      isSetPrice: false, // 自定义价格
      markGoodsInfo: {},
      priceIntelList: [], // 智能价格列表
      loadflag: false,
      page: 1
    }
  },
  methods: {
    ...mapMutations(['setShopItems', 'setProductIds', 'setWatermarkType']),
    onTypeChange (value) {
      this.setWatermarkType(value)
      window.location.reload()
    },
    onSlSize (size) {
      this.acFontSize = size
      this.onFontSizeChange()
    },
    onFontSizeChange () {
      let size = Number(String(this.acFontSize).replace('.', ''))
      if (size > 500) size = 500
      if (size < 1) size = 1
      this.acFontSize = size
      this.fFontSize(this.acFontSize)
    },
    onDelGoods (item, index) {
      this.markGoodsInfo.splice(index, 1)
      const pids = this.XProductIds
      const idx = pids.indexOf(item.numIid)
      if (idx !== -1) pids.splice(idx, 1)
      this.setShopItems(this.markGoodsInfo)
      this.setProductIds(pids)
      if (this.markGoodsInfo.length === 0) {
        return this.$emit('back')
      }
      this.onSlMainGood(this.markGoodsInfo[0])
    },
    onScrollTmp (e) {
      const scroll = e.target
      const scrollH = scroll.scrollHeight - scroll.clientHeight
      const scrollTop = scroll.scrollTop
      if (scrollH - scrollTop < 100 && !this.loadflag) {
        this.loadflag = true
        this.page++
        this.getTmpList()
      }
      // console.log(e.target)
    },
    onCheckCanvas () {
      const priceInfo = {}
      this.markGoodsInfo.forEach(item => {
        priceInfo[item.numIid] = item.markPrice
      })
      return new Promise((resolve, reject) => {
        this.canvasId.forEachObject(item => {
          if (item.myPrice) {
            item.params = priceInfo
          }
        })
        console.log(this.canvasId.size(), 'size')
        if (this.canvasId.size() <= 0) {
          const info = { msg: '请设置水印内容' }
          reject(info)
        }
        const data = {
          content: this.handleJsonStr(),
          templateId: this.tmpId
        }
        resolve(data)
        // 上传缩略图
        // const picBlob = this.fCanvasImg()
        // const files = new window.File([picBlob], 'tmp.png', { type: picBlob.type })
        // httpUploadImage(files).then(res => {
        //   if (res.data.resultStates === 'SUCCEEDED') {
        //     const picUrl = this.XUploadUrl + 'image/' + res.data.images[0]
        //     const data = {
        //       picUrl,
        //       content: this.handleJsonStr(),
        //       templateId: this.tmpId
        //     }
        //     resolve(data)
        //   } else {
        //     const info = { msg: '生成缩略图失败' }
        //     reject(info)
        //   }
        // })
        //   .catch(r => {
        //     const info = { msg: '上传缩略图失败' }
        //     reject(info)
        //   })
      })
    },
    onSelectMenu ({ item, key }) {
      this.activeMenu = key
      console.log(item)
    },
    onColorChange (e) {
      this.fontColor = e.target.value
      this.fFontColor(e.target.value)
    },
    onPosChange (index) {
      this.fPosition(index)
    },
    // 主图列表滚动
    onScroll (type) {
      if (type === 1) { // 左箭头
        this.$refs.mainScroll.scrollLeft -= 800
      } else {
        this.$refs.mainScroll.scrollLeft += 800
      }
    },
    onSlMainGood (item) {
      this.slMainGood = item
      const idKey = 'main' + item.numIid
      // this.fDrawMainImg(item.src)
      const jsonStr = this.$refs[idKey][0].handleToJson()
      this.fLoadJson(jsonStr)
    },
    handleLoadTmp (item, tmpId) {
      this.tmpId = tmpId
      this.slTmp = item
      this.fLoadTmp(item.content, this.slMainGood.markPrice)
        .then(() => {
          this.onUse()
        })
    },
    onSlTmp (item, tmpId) {
      if (this.canvasId.size() === 0) return this.handleLoadTmp(item, tmpId)
      this.$confirm({
        title: '提示',
        content: '应用模板会覆盖当前水印,确定应用',
        onOk: () => {
          this.handleLoadTmp(item, tmpId)
        }
      })
    },
    onTextOptChange (type) {
      this.textOpt = type
      if (type === 1) { // 添加文字
        this.fDrawText(this.textAreaVal || '请输入文字')
        // this.onUse()
      }
      if (type === 2) { // 编辑价格
        this.fUpdatePrice(this.slMainGood.markPrice)
        this.onUse()
      }
    },
    onAddText () {
      this.fDrawText(this.textAreaVal)
      // this.onUse()
    },
    onDelTarget () {
      this.fDelTarget()
      this.onUse()
    },
    onUse () {
      this.handleJsonStr()
      this.XShopItems.forEach(item => {
        const idKey = 'main' + item.numIid
        this.$refs[idKey][0].handleParseJson(this.XFabricJson)
      })
    },
    // 回显画板
    handleInitStr (jsonStr, price, templateId) {
      this.tmpId = templateId
      this.fLoadTmp(jsonStr, price).then(() => {
        this.onUse()
      })
    },
    handleSetPrice () {
      this.slMainGood = this.markGoodsInfo[0]
      this.fUpdatePrice(this.slMainGood.markPrice)
      this.onUse()
    },
    // 智能价格
    handlePriceIntel () {
      this.markGoodsInfo.map(item => {
        item.markPrice = item.lowestPrice
      })
      this.handleSetPrice()
    },
    // 自定义价格
    handlePriceCustm () {
      this.markGoodsInfo.map(item => {
        item.markPrice = item.custmPrice
      })
      this.handleSetPrice()
    },
    // 价格radio
    onPriceChange () { // 1智能 2自定义
      if (this.priceType === 1) this.handlePriceIntel()
      if (this.priceType === 2) this.handlePriceCustm()
    },
    onPriceEdit () {
      this.isSetPrice = true
      this.priceType = 2
    },
    // 设置自定义价格成功
    onPriceOk (data) {
      this.isSetPrice = false
      this.markGoodsInfo = data
      this.handleSetPrice()
    },
    getTmpList () {
      if (this.XWatermarkType === 1) this.tmpList = DataInfo.tmpSquare
      if (this.XWatermarkType === 2) this.tmpList = DataInfo.tmpLong
      if (this.XWatermarkType === 3) this.tmpList = DataInfo.tmpRec
    },
    getGoodsList () {
      if (this.XWatermarkType === 1) this.setShopItems(DataInfo.goodsSquare)
      if (this.XWatermarkType === 2) this.setShopItems(DataInfo.goodsLong)
      if (this.XWatermarkType === 3) this.setShopItems(DataInfo.goodsRec)
    }
  },
  created () {
    const fontSizeList = []
    for (let i = 11; i <= 72; i++) {
      if (i % 2 === 0) {
        fontSizeList.push(i)
      }
    }
    this.fontSizeList = fontSizeList
    this.getTmpList()
    this.getGoodsList()
  },
  mounted () {
    const canvasId = new fabric.Canvas('canvasId')
    this.initData(canvasId)
  },
  watch: {
    'acTarget.type': {
      handler (newValue) {
        if (newValue === 'i-text' || newValue === 'text') {
          this.textAreaVal = this.acTarget.text
          this.activeMenu = 2
          if (this.acTarget.myPrice) {
            this.textOpt = 2
          } else {
            this.textOpt = 1
          }
        } else {
          this.activeMenu = 1
          this.textAreaVal = ''
        }
      },
      immediate: true,
      deep: true
    },
    'acTarget.fill': {
      handler (newValue) {
        if (newValue) this.fontColor = newValue
      },
      immediate: true,
      deep: true
    },
    'acTarget.fontSize': {
      handler (newValue) {
        if (newValue) this.acFontSize = newValue
      },
      immediate: true,
      deep: true
    },
    XShopItems: {
      handler (newValue) {
        if (newValue && newValue.length > 0) {
          const list = [...newValue]
          list.map(item => {
            item.custmPrice = item.lowestPrice
            item.markPrice = item.lowestPrice
          })
          this.markGoodsInfo = list
          this.slMainGood = list[0]
          console.log(364, this.slMainGood)
        }
      },
      deep: true,
      immediate: true
    }
  }
}
</script>

<style lang="less" scoped>
.main_goods {
  overflow-x: auto;
}
.position_box {
  display: flex;
  flex-wrap: wrap;
  width: 200px;
  justify-content: space-between;
  .posi_item {
    width: 50px;
    height: 50px;
    margin: 5px;
    background-color: #dddddd;
    &:hover {
      background-color: #e9f6fe;
      transition: 0.5s all;
    }
  }
}
.mark_page {
  background-color: #ffffff;
  padding: 20px;
  .mark_box {
    display: flex;
    // height: 540px;
    .mark_canvas {
      color: #888888;
      .canvas_tools {
        position: relative;
        height: 46px;
        background: #ffffff;
        border: 1px solid #e8e8e8;
        display: flex;
        align-items: center;
        justify-content: space-between;
        i {
          cursor: pointer;
        }
        .tools_box {
          display: flex;
          align-items: center;
          .select {
            width: 80px;
            margin: 0 5px;
            // background-color: #fff;
            // border: 1px solid #d9d9d9;
            // border-top-width: 1.02px;
            // border-radius: 4px;
            position: relative;
            &:hover .select_hover {
              display: block;
            }
            .ac_font {
              padding: 0 5px;
              width: 100%;
              white-space: nowrap;
              overflow: hidden;
              text-overflow: ellipsis;
              word-break: break-all;
            }
            .select_hover {
              background-color: #fff;
              width: 100%;
              height: 300px;
              overflow-y: auto;
              display: none;
              position: absolute;
              top: 32px;
              left: 0;
              z-index: 999;
              border-radius: 0 0 4px 4px;
              box-shadow: 0px 0px 4px 2px rgba(0, 0, 0, 0.1) inset;
              .select_options {
                padding: 2px 5px;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
                display: flex;
                justify-content: space-between;
                align-items: center;
                cursor: pointer;
                &.active {
                  background-color: #e9f6fe;
                }
                &:hover {
                  background-color: #e9f6fe;
                }
                img {
                  width: 18px;
                  height: 18px;
                }
              }
            }
          }
          .tool_color {
            width: 36px;
            height: 36px;
            border-radius: 4px;
            padding: 0;
            border: none;
            outline: none;
            margin-left: 20px;
            margin-right: 10px;
            cursor: pointer;
          }
        }
        .tool_del {
          position: absolute;
          right: 10px;
          top: 50%;
          transform: translateY(-50%);
          font-size: 28px;
        }
      }
      .canvas_box {
        position: relative;
        .canvas_bg {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
        }
      }
    }
    .mark_menu {
      display: flex;
      width: 100%;
      .edit_menu {
        width: 82px;
        height: 100%;
      }
      .edit_box {
        width: 100%;
        min-width: 410px;
        margin-left: -1px;
        border: 1px solid #e8e8e8;
        // z-index: 2;
        padding: 0 15px;
      }
      .tmp_box {
        .list_box {
          display: flex;
          flex-wrap: wrap;
          img {
            width: 126px;
            // height: 126px;
            // margin-right: 10px;
            border: 1px solid transparent;
            box-shadow: 0px 0px 4px 2px rgba(0, 0, 0, 0.1) inset;
            cursor: pointer;
            &:hover {
              border-color: #1890ff;
            }
            &.active {
              border-color: #1890ff;
            }
          }
        }
      }
      .text_box {
        .text_opts {
          border-bottom: 1px solid #e8e8e8;
          height: 55px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .text_container {
          padding: 15px 0;
          .add_box {
            .tips {
              color: #b9b9b9;
              margin-bottom: 10px;
            }
            .text_area {
              height: 112px;
            }
          }
          .price_box {
            .price_type {
              width: 100%;
              .tips {
                color: #b9b9b9;
                padding-left: 26px;
              }
            }
            .btn {
              margin-top: 10px;
              margin-left: 26px;
            }
          }
        }
      }
    }
  }
  .pic_list {
    margin-top: 20px;
    width: 100%;
    // height: 140px;
    background: #f7f7f7;
    border: 1px solid #e8e8e8;
    position: relative;
    padding: 20px 35px;
    .icon_right,
    .icon_left {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
      font-size: 25px;
      cursor: pointer;
      &:hover {
        color: #1890ff;
      }
    }
    .icon_left {
      left: 5px;
    }
    .icon_right {
      right: 5px;
    }
    .list_box {
      height: 100%;
      display: flex;
      align-items: center;
      // justify-content: space-between;
      // overflow-x: auto;
      .img_item {
        position: relative;
        width: 152px;
        min-width: 152px;
        height: 152px;
        margin-right: 10px;
        align-items: center;
        cursor: pointer;
        border: 1px solid transparent;
        overflow: hidden;
        &:hover {
          border-color: #1890ff;
          .del_icon {
            display: block;
            transition: all 10s;
          }
        }
        &.active {
          border-color: #1890ff;
        }
        .mark {
          width: 100%;
          height: 100%;
          position: absolute;
          top: 0;
          left: 0;
          cursor: pointer;
        }
        .del_icon {
          display: none;
          position: absolute;
          bottom: 0px;
          left: 50%;
          width: 150px;
          transform: translateX(-50%);
          height: 30px;
          background: #000000;
          opacity: 0.7;
          text-align: center;
          vertical-align: middle;
          color: #ffffff;
          font-size: 20px;
          font-weight: bold;
          cursor: default;
          i {
            cursor: pointer;
          }
        }
      }
    }
  }
}
.tmp_list {
  margin-top: 20px;
  .scroll_box {
    overflow-y: auto;
    height: 500px;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
